package com.learn.sc.springbootdemo.aop.aspect;

import com.learn.sc.springbootdemo.aop.DictParam;
import com.learn.sc.springbootdemo.pojo.RetDataBean;
import com.learn.sc.springbootdemo.service.impl.DictParamServiceImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class DictAspect {
    private final Logger logger = LoggerFactory.getLogger(DictAspect.class);
    private static String DICT_SUFFIX = "TextValue";

    @Autowired
    DictParamServiceImpl dictParamService;

    @Pointcut("@annotation(com.learn.sc.springbootdemo.aop.DictParam)")
    public void pointCut(){
    }

    @Around("pointCut() && @annotation(dictParam)")
    public RetDataBean invoke(ProceedingJoinPoint pjp, DictParam dictParam){
        String dictKind = dictParam.dictKey();
        Class clazz = dictParam.getClass();
        Field[] fields = clazz.getDeclaredFields();
        RetDataBean retDataBean = null;

        try {
            retDataBean = (RetDataBean)pjp.proceed();
        } catch (Throwable throwable) {
            logger.error("字典切面异常:"+throwable.getMessage());
        }
        Map resultMap = (Map) retDataBean.getRetData();
        //获取该类别全部字典map
        List<Map<String,String>> dictMap =  dictParamService.getParamKindMap(dictKind);
        //在map中匹配字典项，赋值给TextValue后缀的该字段
        for (Map<String, String> map:dictMap) {
            if(map.get("kind_code").equals(resultMap.get("userSex"))){
                resultMap.put("userSex"+DICT_SUFFIX,map.get("kind_name"));
                break;
            }
        }
        retDataBean.setRetData(resultMap);

        return retDataBean;

    }
}
